<template>
  <section>
    <!--工具条: 高级查询和新增-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="keywordQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onsale">上架</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="offsale">下架</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--分页列表-->
    <!--
  :data="pets" - 列表数据
  highlight-current-row - 当前行高亮
  v-loading="listLoading" - 加载框
  @selection-change="selsChange" - 批量操作要使用的方法
-->
    <el-table :data="pets" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="30">
      </el-table-column>
      <el-table-column type="index" width="30">
      </el-table-column>

      <el-table-column prop="name" label="名称" width="80">
      </el-table-column>

      <el-table-column prop="costprice" label="成本" width="50">
      </el-table-column>
      <el-table-column prop="saleprice" label="售价" width="50">
      </el-table-column>
      <!--<el-table-column prop="resources" label="图片" min-width="60" sortable>
        <template scope="scope">
          <img :src="imgPrefix+scope.row.resources.split(',')[0]" width="50px">
        </template>
      </el-table-column>-->
      <el-table-column prop="state" label="状态" width="90" sortable>
        <template scope="scope">
          <span style="color: #11b95c" v-if="scope.row.state==1">上架</span>
          <span style="color: red" v-else>下架</span>
        </template>
      </el-table-column>
      <el-table-column prop="offsaletime" label="下架时间" width="100" sortable>
      </el-table-column>
      <el-table-column prop="onsaletime" label="上架时间" width="100" sortable>
      </el-table-column>
      <el-table-column prop="createtime" label="创建" width="100" sortable>
      </el-table-column>
      <el-table-column prop="shop.name" label="店铺" width="90" sortable>
      </el-table-column>
      <el-table-column label="领养人" width="90" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.user" style="color: #ff0000">{{scope.row.user.username}}</span>
          <span v-else style="color: #c4c2c1">暂无领养人</span>
        </template>
      </el-table-column>
      <el-table-column label="宠物来源" width="100" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.searchMasterMsgId" style="color: #f300ff">来自寻主消息</span>
          <span v-else style="color: #0022ff">来自店铺饲养</span>
        </template>
      </el-table-column>
      <el-table-column prop="petType.name" label="宠物类型" width="80">
        <!--        <template scope="scope">
                  <span style="color: #20a0ff" v-if="scope.row.parent">{{scope.row.parent.name}}</span>
                  <span style="color: #8c939d" v-else>无类型</span>
                </template>-->
      </el-table-column>
      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="handleSave(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条：批量删除和分页栏-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :current-page="currentPage" :page-size="pageSize" :total="totals" style="float:right;">
      </el-pagination>
    </el-col>

    <!--添加和修改的对话框 : 根据表字段添加-->
    <!--
      :title="title"  - 标题
      :visible.sync="saveFormVisible" - 控制对话框是否显示
      :close-on-click-modal="false" - 点击框外的区域不关闭
        :model="saveForm" - 表单数据是一个对象
        label-width="80px" - 标签的宽度
        :rules="saveFormRules" - 表单项验证
        ref="saveForm" - 给当前表单取一个名称 - 用来做表单验证
    -->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="成本价" prop="costprice">
          <el-input v-model="saveForm.costprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="售价" prop="saleprice">
          <el-input v-model="saveForm.saleprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item prop="logo" label="宠物图片">
          <el-upload class="upload-demo"
                     action="http://localhost:8080/fastDfs/"
                     :on-remove="handleRemove"
                     :on-success="handleSuccess"
                     :file-list="fileList"
                     list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="所属店铺">
          <el-select v-model="saveForm.shopId" placeholder="请选择">
            <el-option
                v-for="item in shops"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="宠物类型">
          <!--
		        :options="options" - 数据 - 无限极树- 集合
            label:'name' - 回显哪一个属性值
            value:'id' - 传值，将id传递给v-model="saveForm.parent_id"
	        -->
          <el-cascader
              v-model="saveForm.typeId"
              :options="petTypeTree"
              :props="{
            	checkStrictly: true,
                label: 'name', // 级联框显示那个属性的值
                value: 'id'    // 回显时需要,回传值的时候也需要
            }"clearable>
          </el-cascader>
        </el-form-item>
        <el-form-item label="简介" prop="intro">
          <!-- v-if="saveForm.petDetail" 修改v-model绑定对象报错问题，v-if对需要显示的数据判断下 -->
          <quill-editor  v-model="saveForm.petDetail.intro" v-if="saveForm.petDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
        <el-form-item label="领养须知" prop="orderNotice" >
          <quill-editor  v-model="saveForm.petDetail.adoptNotice" v-if="saveForm.petDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
      </el-form>
      <!--
         @click.native="saveSubmit" - 点击提交的时候调用saveSubmit方法
         :loading="saveLoading" - 提交的加载加载框
       -->
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>


<script>
//引入Vue的ueditor的资源
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import quillConfig from '../../common/js/quill-config.js';
export default {
  components: {
    quillEditor
  },
  data() {
    return {
      quillOption: quillConfig,
      //列表显示图片的前缀
      imgPrefix: "http://123.207.27.208",

      //1.分页查询相关数据
      pets: [],      //分页数据
      listLoading: false,   //加载框
      totals: 0,            //总数量
      currentPage: 1,       //当前页
      pageSize: 5,          //每页显示的条数

      //2.高级查询
      keyword: '',
      //3.输出相关的数据[无]

      //4.批量删除的相关数据
      sels: [],//列表选中列

      //5.添加和修改的相关数据
      title:'',//标题
      saveFormVisible: false,//添加和修改对话框是否显示
      saveLoading: false,  //保存的忙等框 - 在提交按钮上
      saveFormRules: {     //表单项验证规则
        name: [
          { required: true, message: '请输入宠物名称', trigger: 'blur' }
        ]
      },
      //对话框数据：建议字符串用''，id用null
      saveForm: {
        id: null,
        name: '',
        costprice: 0,
        saleprice: 0,
        typeId: null,
        resources: '',
        state: 0, //默认下架 - 前台看不见这个宠物 - 审核之后才能上架
        shopId: null,
        petDetail:{  //与后端实体类一致
          intro: '',
          adoptNotice: ''
        }
      },
      //所属店铺
      shops:[],
      //宠物类型树
      petTypeTree:[],

      //文件上传相关数据
      fileList: [],

    }
  },
  //自定义方法
  methods: {
    //1.分页查询,获取部门列表
    getPets() {
      //组装参数
      let para = {
        //分页
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        //高级查询
        keyword: this.keyword,
      };
      //显示加载框
      this.listLoading = true;
      //发送异步请求
      this.$http.post("/pet",para).then(res=>{
        this.totals = res.data.totals;
        this.pets = res.data.data;
        //隐藏加载框
        this.listLoading = false;
      }).catch(res=>{
        this.$message.error("网络繁忙,请稍后重试!")
      })
    },

    //2.点击分页的方法
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getPets();
    },

    //3.高级查询的方法
    keywordQuery(){
      this.currentPage = 1;
      this.getPets();
    },
    //点击排序
    handleChange(value) {
      this.saveForm.index = value;
    },

    //4.删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => { //确认框,点击确定走.then中的逻辑
        this.listLoading = true;
        this.$http.delete("/pet/"+row.id).then(res=>{
          this.listLoading = false;
          if(res.data.success){
            this.$message.success("删除成功");
            //计算总页数
            var totalPage = Math.ceil(this.totals/this.pageSize)
            //删除最后一页最后一条数据,而且不能是第一页时,让当前页 = 当前页-1
            if(this.currentPage == totalPage && this.currentPage >1 && (this.totals-1)%this.pageSize==0){
              this.currentPage = this.currentPage - 1;
            }
            this.getPets();
          }else{
            this.$message.error("请检查网络!")//500错误走这里
          }
        }).catch(res=>{
          this.$message.error("请检查网络!")//服务器没开,404,400错误走这里
        })
      }).catch(() => {
      });
    },
    //5.批量删除选项改变时就会触发
    selsChange: function (sels) {
      this.sels = sels;
    },
    //6.批量删除的相关数据和逻辑
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/pet",ids).then(res=>{
          this.listLoading = false;
          if(res.data.success){
            this.$message.success("删除成功");
            this.currentPage = 1;
            this.getPets();
          }else{
            this.$message.error("请检查网络!")//500错误走这里
          }
        }).catch(res=>{
          this.$message.error("请检查网络!")//服务器没开,404,400错误走这里
        })
      }).catch(() => {
      });
    },

    //文件上传的业务逻辑
    handleSuccess(response, file, fileList){
      //1.对resources的处理 - 添加到数据库
      if(this.saveForm.resources){//有值返回true
        this.saveForm.resources = this.saveForm.resources + "," + response.obj;
      }else{
        this.saveForm.resources = response.obj;
      }
      //2.对fileList的处理 - 前端显示图片的
      this.fileList = []; //先清空 - 这个fileList做了绑定，以前是有值【先清空，再添加最新的数据】
      if(this.saveForm.resources){
        // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg,/group1/M00/00/0C/CgAIC2KrUYaAaR-6AADnxcxs4eA746.jpg
        var arr = this.saveForm.resources.split(",")  ;
        for(var i = 0;i<arr.length;i++){
          var item = arr[i]; ///group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg
          this.fileList.push({"url":"http://123.207.27.208" + item});
        }
      }
    },

    //文件删除的业务逻辑
    handleRemove(file, fileList) {
      //1.调用删除接口删除图片
      //Object { url:"http://123.207.27.208/group1/M00/00/E5/CgAIC2Lc_7qAPinhAAEau2OL7dM844.jpg"}
      //console.log(file);
      //http://localhost:8080/fastDfs?path=/group1/M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg
      var path = file.url.substring(file.url.indexOf("/group")); //  /group1/M00/00/E5/CgAIC2Lc_7qAPinhAAEau2OL7dM844.jpg
      this.$http.delete("/fastDfs?path="+path).then(res=>{
        if(res.data.success){
          this.$message.success("删除成功")
        }else{
          this.$message.error("删除失败")
        }
      })

      //2.对resource做处理
      // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg,/group1/M00/00/E5/CgAIC2Lc_7qAPinhAAEau2OL7dM844.jpg,/group1/M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg
      if(this.saveForm.resources){
        var arr = this.saveForm.resources.split(",");
        for(var i = 0;i<arr.length;i++){
          var item = arr[i];
          if(path==item){//找到了删除的图片
            arr.splice(i,1);//删除指定下标i的1张图片
            break;
          }
        }
        this.saveForm.resources = arr.join(",")//按照,将数组中的元素连接
      }


      //3.对fileList的处理 - 前端显示图片的
      this.fileList = []; //先清空 - 这个fileList做了绑定，以前是有值【先清空，再添加最新的数据】
      if(this.saveForm.resources){
        // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg,/group1/M00/00/0C/CgAIC2KrUYaAaR-6AADnxcxs4eA746.jpg
        var arr = this.saveForm.resources.split(",");
        for(var i = 0;i<arr.length;i++){
          var item = arr[i]; ///group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg
          this.fileList.push({"url":"http://123.207.27.208" + item});
        }
      }
    },

    //7.点击修改按钮弹出对话框
    handleSave: function (index, row) {
      //动态修改标题
      this.title = "编辑";
      //回显数据
      this.saveFormVisible = true;
      //将row对象赋值给{}对象,防止列表中的数据同时发生改变
      this.saveForm = Object.assign({}, row);
      //点击修改按钮获取部门树
      this.getPetTypeTree();
      this.getShops();
      //处理fileList - 点击修改能够回显图片
      this.fileList = []; //先清空 - 这个fileList做了绑定，以前是有值【先清空，再添加最新的数据】
      if(this.saveForm.resources){//有值
        // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg,/group1/M00/00/0C/CgAIC2KrUYaAaR-6AADnxcxs4eA746.jpg
        var arr = this.saveForm.resources.split(",");
        for(var i = 0;i<arr.length;i++){
          var item = arr[i]; ///group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg
          this.fileList.push({"url":"http://123.207.27.208" + item});
        }
      }
    },

    //8.点击添加按钮弹出对话框
    handleAdd: function () {
      //动态修改标题
      this.title = "添加";
      this.saveFormVisible = true;
      //将对话框内容清空
      this.saveForm = {
        id: null,
        name: '',
        costprice: 0,
        saleprice: 0,
        typeId: null,
        resources: '',
        state: 0, //默认下架 - 前台看不见这个宠物 - 审核之后才能上架
        shopId: null,
        petDetail:{  //与后端实体类一致
          intro: '',
          adoptNotice: ''
        }
      };
      //点击添加按钮获取部门树
      this.getPetTypeTree();
      this.getShops();
      //清空fileList - 页面不显示图片
      this.fileList=[];
    },
    //9.点击提交按钮,提交数据
    saveSubmit: function () {
      //将所有ref的表单找出来后把ref=saveForm,validate - 验证
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            //显示提交按钮的加载框
            this.saveLoading = true;
            let para = Object.assign({}, this.saveForm);

            //前端无限极树的处理:null,[],[2],[2,7],2
            if(para.typeId==null || para.typeId.length==0){
              para.typeId = null;
            }else if(para.typeId.length){//有值,没有报错,数组[2],[2,7]
              para.typeId = para.typeId[para.typeId.length-1];
            }

            //发送异步请求
            this.$http.put("/pet",para).then(res=>{
              //关闭提交按钮的加载框
              this.saveLoading = false;
              //关闭对话框
              this.saveFormVisible = false;
              if(res.data.success){
                this.$message.success("操作成功");
                this.getPets();
              }else{
                this.$message.error("请检查网络!")//500错误走这里
              }
            }).catch(res=>{
              this.$message.error("请检查网络!")//服务器没开,404,400,405错误走这里
            })
          });
        }
      });
    },
    //获取所有的店铺
    getShops(){
      this.$http.get("/shop").then(res=>{
        this.shops = res.data;
      })
    },
    //11.获取部门树
    getPetTypeTree(){
      this.$http.get("/petType/petTypeTree").then(res=>{
        this.petTypeTree = res.data;
      }).catch(res=>{
      })
    },
    //上架
    onsale(){
      if(this.sels.length<1){
        this.$message.warning("请选择宠物之后再上架!!!");
        return;
      }
      //获取数组中每一个对象的id 并形成新的数组
      var ids = this.sels.map(item => item.id);
      this.$confirm('确定要上架吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.$http.patch("/pet/onsale", ids).then(res => {
          if (res.data.success) { //操作成功
            this.$message.success("操作成功");
            this.getPets();
          } else { //操作失败
            this.$message.error(res.data.msg);
          }
        }).catch(res => {
          this.$message.error("系统繁忙，请稍后重试!!![400,404]");
        })
      }).catch(() => {
      });
    },
    offsale(){
      if(this.sels.length<1){
        this.$message.warning("请选择宠物之后再下架!!!");
        return;
      }
      //获取数组中每一个对象的id 并形成新的数组
      var ids = this.sels.map(item => item.id);
      this.$confirm('确定要下架吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.$http.patch("/pet/offsale", ids).then(res => {
          if (res.data.success) { //操作成功
            this.$message.success("操作成功");
            this.getPets();
          } else { //操作失败
            this.$message.error("系统繁忙，请稍后重试!!![500]"); //后端500错误走这里
          }
        }).catch(res => {
          this.$message.error("系统繁忙，请稍后重试!!![400,404]");
        })
      }).catch(() => {
      });
    },
  },
  mounted() {
    this.getPets();
  }
}

</script>

<style scoped>

</style>